package com.xiaoshuidi.cloud.module.bpm.job.xxljob;

import cn.hutool.core.util.ObjectUtil;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.framework.tenant.core.job.TenantJob;
import com.xiaoshuidi.cloud.module.bpm.dal.dataobject.swo.SwoTicketDO;
import com.xiaoshuidi.cloud.module.bpm.dal.mysql.swo.SwoTicketMapper;
import com.xiaoshuidi.cloud.module.bpm.service.swo.SwoTicketService;
import com.xiaoshuidi.cloud.module.rooms.api.roomhouse.RoomHouseApi;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomHouseRespVo;
import com.xiaoshuidi.cloud.module.system.api.user.AdminUserApi;
import com.xiaoshuidi.cloud.module.system.api.user.dto.AdminUserRespDTO;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 更新服务工单所属部门
 */
@Slf4j
@Component
@TenantJob
@RequiredArgsConstructor
public class RebuildSwoTicketDeptId {

    private final SwoTicketMapper swoTicketMapper;
    private final RoomHouseApi roomHouseApi;
    private final AdminUserApi adminUserApi;

    @XxlJob("rebuild-swo-ticket-dept-id")
    public void rebuildSwoTicket() {
        log.info("更新服务工单所属部门--开始");
        List<SwoTicketDO> swoTicketDOS = swoTicketMapper.selectList();

        swoTicketDOS.stream().forEach(swoTicketDO -> {
            if (ObjectUtil.isNotEmpty(swoTicketDO.getRoomId())) {
                RoomHouseRespVo roomHouseRespVo = roomHouseApi.getRoomHouseinfoById(swoTicketDO.getRoomId()).getCheckedData();
                swoTicketDO.setDeptId(ObjectUtil.isNotEmpty(roomHouseRespVo) ? roomHouseRespVo.getDeptId() : null);
            } else {
                AdminUserRespDTO adminUserRespDTO = adminUserApi.getUser(Long.valueOf(swoTicketDO.getCreator())).getCheckedData();
                swoTicketDO.setDeptId(ObjectUtil.isNotEmpty(adminUserRespDTO) ? adminUserRespDTO.getDeptId() : null);
            }
        });

        if(ObjectUtil.isNotEmpty(swoTicketDOS)){
            swoTicketMapper.updateBatch(swoTicketDOS, swoTicketDOS.size());
        }
        log.info("更新服务工单所属部门--结束");

    }

}
